package cn.com.cetccst.mdmdemo;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Process;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.zdk.mdm.engine.MdmDeviceAdminReceiver;
import com.zdk.mg.agent.R;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import cn.com.cetccst.mdm.engine.IMDMEngine;
import cn.com.cetccst.mdm.MDMManager;
import cn.com.cetccst.mdm.engine.NotSupportException;
import cn.com.cetccst.mdmdemo.utils.FileUtils;
import cn.com.cetccst.mdmdemo.utils.Logger;
import cn.com.cetccst.mdmdemo.utils.ThreadSafeToast;
import cn.com.cetccst.mdmdemo.utils.ToolbarActivity;

public class MainActivity extends ToolbarActivity {
    private ListView listView;
    private ListAdapter adapter;
    private List<Item> items = new ArrayList<>();
    private IMDMEngine engine;
    private BroadcastReceiver deviceAdminReceiver;

    private final static String[] permissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initToolbarWithoutBack("MDM接口测试");
        listView = findViewById(R.id.listBox);
        adapter = new ListAdapter(this);
        listView.setAdapter(adapter);
        engine = MDMManager.getInstance().getMdmEngine();
        deviceAdminReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                initWithDeviceAdmin();
            }
        };
        LocalBroadcastManager.getInstance(this).registerReceiver(deviceAdminReceiver, MdmDeviceAdminReceiver.receiverFilter);
        requestDeviceAdmin();
//        DoubleApnManager.init(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(deviceAdminReceiver);
    }

    private void requestDeviceAdmin() {
        if (!engine.isActiveDeviceAdmin()) {
            Logger.log("device admin is not ready.");
            engine.setActiveDeviceAdmin(this);
        } else {
            initWithDeviceAdmin();
        }
    }

    private void initWithDeviceAdmin() {
        getSupportActionBar().setTitle(MDMManager.getInstance().getMdmName() + ":" + engine.getName());
        loadSettings();
        checkPermission();
    }

    private void loadSettings() {
        if (!items.isEmpty()) {
            items.clear();
        }
        items.add(new Item("禁用蓝牙", "Bluetooth"));
        items.add(new Item("禁用相机", "Camera"));
        items.add(new Item("禁用WIFI", "Wifi"));
        items.add(new Item("禁用麦克风", "MicroPhone"));
        items.add(new Item("禁用扩展存储", "ExternalStorage"));
        items.add(new Item("禁用截屏", "ScreenShot"));
        items.add(new Item("禁用恢复出厂设置限制", "RestoreFactory"));
        items.add(new Item("禁用NFC", "NFC"));
        items.add(new Item("禁用移动热点", "MobileHotSpot"));
        items.add(new Item("禁用语音呼出", "Callout"));
        items.add(new Item("禁用短信", "Sms"));
        items.add(new Item("禁用移动网络数据", "MobileData"));
        items.add(new Item("禁用音量调节下按键", "VolumeDown"));
        items.add(new Item("禁用修改时间/时区", "AutoTime"));
        items.add(new Item("禁用USB传输", "UsbData"));
        items.add(new Item("禁用USB调试", "UsbDebug"));
        items.add(new Item("禁用操作系统升级", "SystemUpgrade"));
        items.add(new Item("禁用位置信息", "GPS"));
        items.add(new Item("强制GPS开启", "ForceGPS"));
        items.add(new Item("禁用未知来源", "UnknownSource"));
        items.add(new Item("启用Device Owner", "DeviceOwner"));
        items.add(new Item("禁止取消设备管理器", "RemoveDeviceAdmin"));
        items.add(new Item("禁止添加用户/隐私空间", "AddUser"));
        items.add(new Item("禁用复制粘贴", "CopyPaste"));
        items.add(new Item("禁用指纹识别", "FingerPrint"));
        items.add(new Item("独占系统(hw)", "SingleApp"));
        adapter.notifyDataSetChanged();
    }

    private int getSetting(String name) {
        int ret = -1;
        try {
            Method method = IMDMEngine.class.getDeclaredMethod("is" + name + "Controlled");
            boolean s = (boolean) method.invoke(engine);
            ret = s ? 1 : 0;
        } catch (NotSupportException e) {
            ThreadSafeToast.show("不支持：" + e.getMessage());
        } catch (Exception e) {
            Throwable root = getRootException(e);
            if (root instanceof NotSupportException) {
                ThreadSafeToast.show("不支持：" + e.getMessage());
            } else if (root instanceof ReflectiveOperationException) {
            } else {
                ThreadSafeToast.show(e.getMessage());
            }
            e.printStackTrace();
        }
        return ret;
    }

    private void setSetting(String name, boolean disabled) {
        try {
            Method method = IMDMEngine.class.getDeclaredMethod("control" + name, boolean.class);
            method.invoke(engine, disabled);
        } catch (NotSupportException e) {
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handleSettingChanged(Item item, boolean disabled) {
        item.setDisabled(disabled);
        setSetting(item.name, disabled);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.unregister_device_admin_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.unregister) {
            File dataDir = getDataDir();
            FileUtils.delete(dataDir.getAbsolutePath());
            engine.removeDeviceAdmin();
            Process.killProcess(Process.myPid());
            return true;
        } else if (id == R.id.others) {
            startActivity(new Intent(this, FunctionsActivity.class));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private boolean checkPermission() {
        boolean hasPermissions = (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
        if (!hasPermissions) {
            ActivityCompat.requestPermissions(this, permissions, 2000);
        }
        return hasPermissions;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10000) {
            if (resultCode == Activity.RESULT_OK) {
                Logger.log("set device admin complete");
                initWithDeviceAdmin();
            } else {
                finish();
            }
        } else if (requestCode == 2000) {
            if (resultCode == Activity.RESULT_OK) {

            } else {
                finish();
            }
        }
    }

    private Throwable getRootException(Exception e) {
        Throwable root = e;
        while (root.getCause() != null) {
            root = root.getCause();
        }
        return root;
    }

    private class Item {
        private String label;
        private String name;
        private int disabled;

        public Item(String label, String name) {
            this.label = label;
            this.name = name;
            if (engine != null) {
                disabled = getSetting(name);
            }
        }

        public String getLabel() {
            return label;
        }

        public void setLabel(String label) {
            this.label = label;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getDisabled() {
            return disabled;
        }

        public void setDisabled(boolean disabled) {
            this.disabled = disabled ? 1 : 0;
        }
    }

    private final class ListAdapter extends BaseAdapter {
        private Context context;

        public ListAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View convertView, ViewGroup viewGroup) {
            View view = View.inflate(context, R.layout.list_item_check, null);
            fillItem(view, i);
            return view;
        }

        private void fillItem(View listItem, int index) {
            CheckBox checkBox = listItem.findViewById(R.id.item);
            checkBox.setTag(String.valueOf(index));
            checkBox.setText(items.get(index).label);
            int disabled = items.get(index).getDisabled();
            checkBox.setEnabled(disabled >= 0);
            checkBox.setChecked(disabled == 1);
            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                    handleSettingChanged(items.get(index), checked);
                }
            });
        }
    }

}